package cz.muni.fi.pa165.sme.web.panels.sportActivity;

import cz.muni.fi.pa165.sme.api.SportActivityService;
import cz.muni.fi.pa165.sme.api.to.SportActivityTO;
import cz.muni.fi.pa165.sme.web.common.ErrorBehavior;
import cz.muni.fi.pa165.sme.web.fo.SportActivityFO;
import cz.muni.fi.pa165.sme.web.pages.sportActivity.ActivityListPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.NumberTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.visit.IVisit;
import org.apache.wicket.util.visit.IVisitor;
import org.apache.wicket.validation.validator.MinimumValidator;
import org.springframework.core.convert.ConversionService;

/**
 * @author jirankova
 */
public class ActivityForm extends Panel {

	@SpringBean
	private SportActivityService sportActivityService;

	@SpringBean(name = "conversionServiceFe")
	private ConversionService conversionService;

	public ActivityForm(final String id, final IModel<SportActivityFO> model) {
		super(id, model);

		//title, speed
		final FormComponent<String> title = new TextField<String>("title");
		title.setRequired(true);

		final FormComponent<Float> speed = new NumberTextField<Float>("speed").add(new MinimumValidator<Float>(0f));

		final Form<SportActivityFO> activityForm = new Form<SportActivityFO>("activityForm", model) {
			@Override
			protected void onSubmit() {
				super.onSubmit();
				final SportActivityFO sportActivityFO = model.getObject();
				final SportActivityTO activityTO = conversionService.convert(sportActivityFO, SportActivityTO.class);

				if(sportActivityService.exists(activityTO)) {
					sportActivityService.updateSportActivity(activityTO);
				} else {
					sportActivityService.createSportActivity(activityTO);
				}

				setResponsePage(ActivityListPage.class);
			}
		};

		activityForm.add(title);
		activityForm.add(speed);

		add(activityForm);

		activityForm.visitChildren(FormComponent.class, new IVisitor<FormComponent<?>, IVisit<Void>>() {
			@Override
			public void component(final FormComponent<?> object, final IVisit<IVisit<Void>> visit) {
				object.add(new ErrorBehavior());
				visit.dontGoDeeper();
			}
		});

		final FeedbackPanel feedbackPanel = new FeedbackPanel("feedbackPanel");
		feedbackPanel.setOutputMarkupId(true);
		add(feedbackPanel);
	}
}
